// https://leetcode-cn.com/problems/reverse-nodes-in-k-group/submissions/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head) {
        ListNode* pre = NULL;
        while (head) {
            ListNode* tmp = head->next;
            head->next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* tmp = head;
        int times = k - 1;
        while (tmp && times--) {
            tmp = tmp->next;
        }
        if (!tmp) return head;
        ListNode* next = tmp->next;
        tmp->next = NULL;
        ListNode* new_head = reverse(head);
        head->next = reverseKGroup(next, k);
        return new_head;
    }
};